﻿// Copyright © Armen Kirakosyan
// armen@kirakosyan.com

using System;

[assembly: CLSCompliant(true)]
namespace Validator
{
    using System.Collections.Specialized;
    using System.Net;
    using System.Text;
    using System.Threading;

    public static class Client
    {
        private const string ServerAPIUrl = @"http://validator.w3.org/check";
        
        public static ValidatorResult Check(Uri url)
        {
            // Thread should sleep 1 second, if multiple requests will be sent
            // Thread.Sleep(1000);

            var wc = new WebClient();

            // build query string
            wc.QueryString.Add("uri", url.OriginalString);
            wc.QueryString.Add("output", "soap12");

            var response = wc.DownloadString(ServerAPIUrl);
            
            wc.Dispose();

            var validatorResult = new ValidatorResult(response);

            return validatorResult;
        }

        public static ValidatorResult Check(string html)
        {
            // Thread should sleep 1 second
            Thread.Sleep(1000);

            var wc = new WebClient();

            // build form values
            var formValues = new NameValueCollection {{"output", "soap12"}, {"uploaded_file", html}};

            var responseBuff = wc.UploadValues(ServerAPIUrl, "POST", formValues);
            var response = Encoding.UTF8.GetString(responseBuff);

            wc.Dispose();

            var validatorResult = new ValidatorResult(response);

            return validatorResult;
        }
    }
}
